﻿using Business.AspNet;
using Business.Core;
using Business.Core.Annotations;
using Business.Core.Result;
using Common;
using DataModel;
using FangPage.Common;
using LinqToDB;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProjectManager.User;
using ProjectManager.User.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;


namespace ProjectManagerSys.backoffice.file
{
    public class FileMerber : Common.BusinessBase
    {

        #region //上传文件
        [Doc("上传文件", Group = "文件管理")]
        public virtual async Task<dynamic> UpLoadFiles()
        { 
            long size = 0;
            List<BJSYS_ARRACH> list = new List<BJSYS_ARRACH>();
            object obj = new object();
            try
            {
                //var files = Request.Form.Files;
                foreach (var file in Common.HttpContext.Current.Request.Form.Files)
                {
                    var filename = ContentDispositionHeaderValue
                        .Parse(file.ContentDisposition)
                        .FileName
                        .Trim('"');

                    #region 文件处理相关方法,待整理
                    string fileExt = FileHelper.GetFileExt(filename); //文件扩展名，不含“.”
                    string oldfileName = filename.Substring(filename.LastIndexOf(@"\") + 1); //取得原文件名
                    string newFileName = FileHelper.GetDateFile() + "." + fileExt; //随机生成新的文件名
                    string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名
                    string upLoadPath = System.IO.Path.Combine("/uploads", FileHelper.GetDateDir());

                    string fullUpLoadPath = System.IO.Path.Combine(FPPath.GetMapPath("/") + upLoadPath);

                    string upfilename = FileHelper.GetDateFile() + "_" + oldfileName; //上传文件名称
                    string newFilePath = System.IO.Path.Combine(upLoadPath, upfilename);
                    //upLoadPath + upfilename;//上传目录相对路径 + 文件名称 存数据库路径
                    //string newThumbFilePath = System.IO.Path.Combine(upLoadPath, newThumbnailFileName);//缩略图
                    using (var con = Data.DB.GetConnection())
                    {
                        //检查文件扩展名是否合法
                        var oType = con.BJSYS_ATTACH_TYPE.Where(c=>c.TYPE==fileExt).FirstOrDefault();
                        if (oType == null)
                        {
                            obj = new { flat = -1,message="（"+fileExt + "）文件格式不允许上传" };
                            return obj;
                        }
                        size = file.Length;
                        //检查文件的大小是否合适
                        if (size > oType.MAXSIZE)
                        {
                            obj = new { flat = -2, message = "上传文件大小超过最大限制" };
                            return obj;
                        }
                        //检查上传的物理路径是否存在，不存在则创建
                        if (!Directory.Exists(fullUpLoadPath))
                        {
                            Directory.CreateDirectory(fullUpLoadPath);
                        }
                        int width = 0;
                        int height = 0;
                        string fullPathName = System.IO.Path.Combine(fullUpLoadPath, upfilename);
                        //先存原件，有原件的情况下才能生成缩略图
                        using (FileStream fs = System.IO.File.Create(fullPathName))
                        {
                            file.CopyTo(fs);
                            fs.Flush();

                        }
                        //如果是图片，则生成缩略图
                        //string fullPathNameThumbnail = System.IO.Path.Combine(fullUpLoadPath, newThumbnailFileName);
                        //if (FileHelper.IsImage(fileExt))
                        //{
                        //    Thumbnail.MakeThumbnailImage(fullPathName, fullPathNameThumbnail, 460, 250, "Cut");
                        //}
                        //else
                        //{
                        //    newThumbFilePath = "";
                        //}
                        #endregion

                        //判断是否上传OK
                        if (File.Exists(fullPathName) == false)
                        {
                            obj = new { flat = -2, message = "上传失败" };
                            return obj;                           
                        }
                        //获取图片的宽高
                        Common.FileHelper.GetImageWidthHeight(fileExt, fullPathName, out width, out height);

                        var upfile = new BJSYS_ARRACH();
                        string guid = Guid.NewGuid().ToString();
                        upfile.ID = guid;
                        upfile.FILETYPE = fileExt;
                        upfile.FILENAME = oldfileName;
                        newFilePath = newFilePath.Replace(@"\", "/");
                        upfile.FILEPATH = newFilePath;
                        upfile.FILESIZE = (int)size;
                        //newThumbFilePath = newThumbFilePath.Replace(@"\", "/");
                        upfile.HEIGHT = height;
                        upfile.WIDTH = width;
                        upfile.CREATETIME = DateTime.Now;
                        upfile.UPDATETIME = DateTime.Now;
                        upfile.ACTIVE = 1;
                        upfile.EFFECT = 0;
                        upfile.READS = 0;
                        upfile.DOWNLOADS = 0;
                        AuthInfo authinfo = Logins.Authorize();
                        upfile.CREATENAME = authinfo.userid;
                        //con.BeginTransaction();
                        var i = await con.InsertAsync(upfile);
                        //con.Commit();
                        list.Add(upfile);
                    }
                }

                obj = new { flat = 1, message = "上传成功",list = list };
                return obj;
            }
            catch (Exception ex)
            {
                obj = new { flat = -3, message = "内部错误，请联系技术人员" };
                return obj;
                
            }

        }
        #endregion

        #region //修改上传的文件
        [Doc("修改文件", Group = "文件管理")]
        public virtual async Task<dynamic> updateFile(Arg<List<BJSYS_ARRACH>> arg,string attachcode, string operation)
        {
            var flag = 0;
            string message = "";
            try
            {
                using (var con = Data.DB.GetConnection())
                {
                    con.BeginTransaction();
                    foreach (var item in arg.Out)
                    {
                        var oAttach = con.BJSYS_ARRACH.Where(c => c.ID == item.ID).FirstOrDefault();
                        if (operation == "delete")
                        {
                            oAttach.ACTIVE = 0;
                        }
                        if (operation == "update")
                        {
                            oAttach.ATTACHCODE = attachcode;
                            oAttach.UPDATETIME = DateTime.Now;
                            //oAttach.CREATENAME = userid;
                        }
                        flag += await con.UpdateAsync(oAttach);
                    }
                    if (flag == arg.Out.Count)
                    {
                        con.Commit();
                        message = "图片上传成功";
                    }
                    else
                    {
                        con.Rollback();
                        flag = -1;
                        message = "内部错误，请联系技术人员";
                    }
                }
                    
            }
            catch (Exception ex)
            {
                flag = -2;
                message = "内部错误，请联系技术人员";
            }
            object obj = new { result = flag,message=message, list = arg.Out };
            return (obj);
        }
        #endregion

        #region //删除上传的文件
        [Doc("删除文件", Group = "文件管理")]
        public virtual async Task<dynamic> DeleteFile(string id)
        {
            var flag = 0;
            string message = "";
            try
            {
                using (var con = Data.DB.GetConnection())
                {
                    var oAttach = con.BJSYS_ARRACH.Where(c => c.ID == id).FirstOrDefault();
                    oAttach.ACTIVE = 0;
                    flag = await con.UpdateAsync(oAttach);
                }

            }
            catch (Exception ex)
            {
                flag = -2;
                message = "内部错误，请联系技术人员";
            }
            object obj = new { result = flag, message = message};
            return (obj);
        }
        #endregion

        #region //根据附件编码获取附件列表
        [Doc("根据附件编码获取附件列表", Group = "文件管理")]
        public virtual async Task<dynamic> GetFileAttachCode(string attachCode)
        {
            var flag = 0;
            string message = "";
            List<BJSYS_ARRACH> list = new List<BJSYS_ARRACH>();
            try
            {
                using (var con = Data.DB.GetConnection())
                {
                    list = con.BJSYS_ARRACH.Where(c => c.ATTACHCODE == attachCode && c.ACTIVE==1 && c.EFFECT==1).ToList();
                    flag = 1;
                }

            }
            catch (Exception ex)
            {
                flag = -2;
                message = "内部错误，请联系技术人员";
            }
            object obj = new { flag = flag, message = message, list= list };
            return (obj);
        }
        #endregion

        
    }
}
